<?php
/**
 * run with command
 * php start.php start
 */

namespace addons\shopro\command;

use addons\shopro\exception\Exception;
use addons\shopro\model\NotificationConfig;
use addons\shopro\model\UserOauth;
use addons\shopro\model\UserWalletLog;
use think\Db;
use think\exception\HttpResponseException;
use addons\shopro\model\User;
use addons\shopro\model\UserMsg;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
/**
 *
 */
class Msg extends Command
{

    protected function configure()
    {
        $this->setName('shopro:msg')
            ->setHelp('消息通知')
            ->setDescription('农场 消息通知');
    }

    protected function execute(Input $input, Output $output)
    {
        $data = db('shopro_user_claim')->where(['status'=>1,'is_warn'=>1])->select();
        if($data){
            $UserMsg = new UserMsg();
            $time    =  strtotime(date('Y-m-d'));
            $r_1 = $r_2 = $r_3 = '';
            foreach ($data as $k=>$v){
                if($v['water_time']==0){
                    $water_day    = 1;
                }else{
                    $water_time   = strtotime(date('Y-m-d',$v['water_time']));
                    $water_day    = ($time-$water_time)/86400;
                }
                if($v['feeding_time'] == 0){
                    $feeding_day  = 1;
                }else{
                    $feeding_time = strtotime(date('Y-m-d',$v['feeding_time']));
                    $feeding_day  = ($time-$feeding_time)/86400;
                }

                if($v['sweep_time'] == 0){
                    $sweep_day    = 1;
                }else{
                    $sweep_time   = strtotime(date('Y-m-d',$v['sweep_time']));;
                    $sweep_day    = ($time-$sweep_time)/86400;
                }
                $goodsInfo = db('nc_goods')->where(['id'=>$v['nc_goods_id']])->find();
                if($goodsInfo){
                    $inser['user_claim_id']  = $v['id'];
                    $inser['user_id']        = $where['user_id']  =  $v['user_id'];
                    $inser['type']           = $v['type'];
                    $where['wallet_type']    = 'score';
                    $where['item_id']        = $v['id'];
                    $deduction               = 0;
                    $out_coom                = '';
                    if($water_day>0){
                        //喂水
                        $day = $water_day;
                        $typemsg   = $v['type']==1?'喂水':'浇水';
                        if($day >= $goodsInfo['day_restrict']){
                            $out_coom .= $typemsg;
                            $deduction += $goodsInfo['deduction'];
                        }
                        $where['type']        = 'nc_water';
                        $count = db('shopro_user_wallet_log')->where($where)->whereTime('createtime', 'd')->count();
                        if(!$count){
                            if($v['type']==1){
                                $inser['memo']    = "您 ".$typemsg.' 的 '.$goodsInfo['title'].'已经'.$day.' 天没喝水了';
                            }else{
                                $inser['memo']    = "您 ".$typemsg.' 的 '.$goodsInfo['title'].'已经'.$day.' 天没浇水了';
                            }
                           $r_1 = $UserMsg->create($inser);
                            $this->tongzhi($v['user_id'],$typemsg,$inser['memo']);
                        }
                    }

                    if($feeding_day>0){
                        //喂食
                        $day = $feeding_day;
                        $typemsg   = $v['type']==1?'喂食':'施肥';

                        if($day >= $goodsInfo['day_restrict']){
                            $deduction +=$deduction;
                            $out_coom  .= '、'.$typemsg;
                        }
                        $where['type']            = 'nc_feeding';
                        $count = db('shopro_user_wallet_log')->where($where)->whereTime('createtime', 'd')->count();
                        if(!$count){
                            if($v['type']==1){
                                $inser['memo']    = "您 ".$typemsg.' 的 '.$goodsInfo['title'].'已经'.$day.' 天没喂食了';
                            }else{
                                $inser['memo']    = "您 ".$typemsg.' 的 '.$goodsInfo['title'].'已经'.$day.' 天没施肥了';
                            }
                            $r_2 = $UserMsg->create($inser);
                            $this->tongzhi($v['user_id'],$typemsg,$inser['memo']);
                        }
                    }

                    if($sweep_day>0){
                        //打扫
                        $day = $sweep_day;
                        $typemsg   = $v['type']==1?'打扫农舍':'除草';
                        if($day >= $goodsInfo['day_restrict']){
                            $deduction +=$deduction;
                            $out_coom  .= '、'.$typemsg;
                        }
                        $where['type']   = 'nc_sweep';
                        $count = db('shopro_user_wallet_log')->where($where)->whereTime('createtime', 'd')->count();
                        if(!$count){
                            if($v['type']==1){
                                $inser['memo']    = "您已经".$day.' 天没给'.$goodsInfo['title'].' 打扫农舍了';
                            }else{
                                $inser['memo']    = "您 ".$typemsg.' 的 '.$goodsInfo['title'].'已经'.$day.' 天没除草了';
                            }
                            $r_3 = $UserMsg->create($inser);
                            $this->tongzhi($v['user_id'],$typemsg,$inser['memo']);
                        }
                    }
                    if($water_day >= $goodsInfo['failure_num'] && $feeding_day>=$goodsInfo['failure_num'] && $sweep_day>=$goodsInfo['failure_num']){
                        $inser['memo'] = "您长时间没有照顾您的 ".$goodsInfo['title'].'系统已收回';
                        $up['status'] = 2;
                        $UserMsg->create($inser);
                    }
                    if($r_1 || $r_2 || $r_3){
                        echo "操作成功";
                        $up['is_warn'] = 2;
                        db('shopro_user_claim')->where(['id'=>$v['id']])->update($up);//自动失效
                    }
                    if($deduction > 0){
                        $memo2 = "长时间没有".$out_coom.' 系统扣除';
                        $this->score($deduction, $v['user_id'],'nc_take_out',$v['id'],$memo2);//扣除积分
                    }
                }
            }
        }else{
            echo "无数据";
        }
    }

    public  function score($score, $user, $type = '', $type_id = 0, $memo = '', $ext = [])
    {
        // 判断用户
        if (is_numeric($user)) {
            $user = User::get($user);
        }
        if ($user) {
            $after  = $user->score - $score;//变更后
            $before = $user->score;//变更前
            if($after < 0){
                $after = 0;
            }
            try {
                $user->score = $after;
                $user->save();
                UserWalletLog::write($user, -$score, $before, $after, $type, $type_id, "score", $memo, $ext);
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        }
    }


    public function tongzhi($user_id,$rwname,$warn){
        $Wechat = new \addons\shopro\library\Wechat('wxMiniProgram');
        $oauth = UserOauth::where('user_id',$user_id)
            ->where('provider', 'Wechat')
            ->where('platform', 'wxMiniProgram')->find();
        $config = NotificationConfig::where(['event'=>'nc_character'])->find();
        $arr    = json_decode($config['content'],true);
        $data = array(
            "touser" => $oauth['openid'], // 接收用户openid
            "template_id" => $arr['template_id'], // 模板消息ID
            "page" => "/pages/index/farm", // 跳转小程序页面路径
            "data" => array(
                $arr['fields'][0]['template_field'] => array(
                    "value" => $rwname
                ),
                $arr['fields'][1]['template_field'] => array(
                    "value" => $warn
                ),
                $arr['fields'][2]['template_field'] => array(
                    "value" => date('Y-m-d').' 23:59:59'
                ),
            )
        );
       $Wechat->sendMessage($data);
    }

}
